<template>
  <div class="camera-page">
    <header class="header">
      <h1 class="title">FAMWELL</h1>
      <button class="menu-btn">
        <span></span>
        <span></span>
        <span></span>
      </button>
    </header>

    <div class="image-preview">
      <div class="preview-item" v-for="(image, index) in images" :key="index">
        <img :src="image" alt="preview" />
        <button class="delete-btn" @click.stop="deleteImage(index)">
          <span>×</span>
        </button>
      </div>
      <div class="empty-preview" v-if="images.length === 0">
        <p>No images captured yet</p>
      </div>
    </div>

    <div class="capture-btn" @click="captureImage">
      <span class="plus">+</span>
      <span class="text">Add Capture</span>
    </div>
    <input 
      type="file" 
      ref="fileInput" 
      accept="image/*" 
      style="display: none;"
      @change="onFileSelected" multiple
    />

    <button class="submit-btn" @click="handleSubmit">Submit</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElLoading } from 'element-plus';
import { getApiBaseUrl, currentEnv, ENV } from '../config/env.js';

const envOptions = Object.keys(ENV);
const currentEnvironment = ref(currentEnv);

const router = useRouter();
const images = ref([]);
const fileInput = ref(null);

const captureImage = () => {
  // Trigger file input click to open camera
  fileInput.value.click();
};

// const onFileSelected = (event) => {
//   const file = event.target.files[0];
//   if (file) {
//     const reader = new FileReader();
//     reader.onload = (e) => {
//       // Add the captured image to the images array
//       images.value.push(e.target.result);
//     };
//     reader.readAsDataURL(file);
//   }
//   // Reset file input to allow selecting the same file again
//   event.target.value = '';
// };
const onFileSelected = (event) => {
  const files = event.target.files;
  if (files.length > 0) {
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const reader = new FileReader();
      reader.onload = (e) => {
        // Add the captured image to the images array
        images.value.push(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  }
  // Reset file input to allow selecting the same file again
  event.target.value = '';
};    

const deleteImage = (index) => {
  // Remove the image at the specified index
  images.value.splice(index, 1);
};

const handleEnvChange = () => {
  // 更新环境配置文件中的当前环境
  window.localStorage.setItem('currentEnv', currentEnvironment.value);
  location.reload(); // 刷新页面以应用新的环境配置
};

const handleSubmit = async () => {
  if (images.value.length === 0) {
    alert('请先添加图片');
    return;
  }

  const loadingInstance = ElLoading.service({
    text: '正在分析图片，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  try {
    const response = await fetch(`${getApiBaseUrl()}/detectDrugs`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        images: images.value
      })
    });

    if (!response.ok) {
      throw new Error('请求失败');
    }

    const drugsData = await response.json();
    if (!drugsData.success) {
      throw new Error("分析失败");
    }
    const data=drugsData.data

    // const data = {'MDMA': {'c': 1, 't': 1}, 'MET': {'c': 1, 't': 1}, 'MOP': {'c': 0, 't': 1}, 'MTD': {'c': 1, 't': 0}}
    
    console.log(data);
    
    router.push({
      name: 'Result',
      state: {
        drugs: JSON.stringify(data)
      }
    });
  } catch (error) {
    alert('分析失败：' + error.message);
  } finally {
    loadingInstance.close();
  }
};
</script>

<style scoped>
.camera-page {
  background-color: #FFF5F3;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  position: relative;
  padding-bottom: 200px; /* Add space for fixed buttons */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #000080;
  margin: 0;
}

.env-switch {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.env-select {
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
  color: #666;
  background-color: white;
  cursor: pointer;
}

.menu-btn {
  background: none;
  border: none;
  padding: 5px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-btn span {
  display: block;
  width: 20px;
  height: 2px;
  background-color: #000;
}

.image-preview {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 30px;
}

.preview-item {
  aspect-ratio: 1;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: rgba(255, 0, 0, 0.8);
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.empty-preview {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 8px;
  color: #666;
}

.capture-btn {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: fixed;
  left: 50%;
  bottom: 100px;
  transform: translateX(-50%);
  z-index: 10;
}

.plus {
  font-size: 36px;
  line-height: 1;
  color: #666;
}

.text {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.submit-btn {
  width: calc(100% - 40px); /* Account for parent padding */
  padding: 15px;
  background-color: #F88379;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  position: fixed;
  left: 20px;
  bottom: 20px;
  z-index: 10;
}
</style>